package com.learn.filter;

import com.alibaba.fastjson.JSON;
import com.learn.pojo.Result;
import com.learn.util.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String url = req.getRequestURI();

        //看请求的资源是否为login
        if(url.contains("login")){
            log.info("登录操作，放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //看Token是否为空
        String jwt = req.getHeader("token");
        if(jwt == null || jwt.trim().isEmpty() || jwt.split("\\.").length != 3 ){
            log.info("token为空，请登录");
            Result error = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(error);
            resp.getWriter().write(json);
            return;
        }

        //如果JWT错误，则返回错误信息
        try {
            JwtUtil.parseJwt(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token错误，请登录");
            Result error = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(error);
            resp.getWriter().write(json);
            return;
        }

        log.info("token有效，放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
